package com.pansoft.mobilemallpay.pays;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.widget.Toast;

import com.efounder.http.UniversalRequestManager;
import com.efounder.util.DialogUtils;
import com.efounder.utils.ResStringUtil;
import com.google.gson.Gson;
import com.pansoft.mobilemallpay.R;
import com.pansoft.mobilemallpay.bean.WxPayOrderResultBean;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.HashMap;

/**
 * Created by meijun on 17-11-29.
 */
public class WxPay implements PayInter {
    public static final String ACTIONG_MESSAGE = "WXPAY_RESULT_LISTENER";
    private Context mContext = null;
    private String url;
    private HashMap paramsMap;

    public WxPay(Context mContext) {
        this.mContext = mContext;
    }

    public void showToast(String msg) {
        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void pay(OnPayListener payListener) {
        if (payListener == null) {
            payListener = OnPayListener.DEFAULT_LISTENER;
        }
        final OnPayListener finalPayListener = payListener;
        //注册广播监听
        final BroadcastReceiver receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String msg = intent.getStringExtra("msg");
                String code = intent.getStringExtra("code");
                if (!TextUtils.isEmpty(msg) && !TextUtils.isEmpty(code)) {
                    if ("0".equals(code)) {
                        finalPayListener.onPaySuccess();
                        LocalBroadcastManager.getInstance(mContext).unregisterReceiver(this);

                    } else {
                        nofityError(finalPayListener, this, msg);

                    }
                }
            }
        };
        LocalBroadcastManager.getInstance(mContext).registerReceiver(receiver, new IntentFilter(ACTIONG_MESSAGE));
        DialogUtils.showProgressDialog(ResStringUtil.getString(R.string.common_text_please_wait));

        paramsMap.put("dev","android");
        UniversalRequestManager.
                getInstance(mContext).
                requestAsyn(url, 1, paramsMap, new UniversalRequestManager.ReqCallBack<Object>() {
                    @Override
                    public void onReqSuccess(Object result) {
                        DialogUtils.dismissProgressDialog();
                        Gson gson = new Gson();
                        try {
                            WxPayOrderResultBean wxPayOrderResultBean = gson.fromJson(result.toString(), WxPayOrderResultBean.class);
                            if (wxPayOrderResultBean != null && "success".equals(wxPayOrderResultBean.getResult())) {
                                String appid = wxPayOrderResultBean.getAppid();
                                IWXAPI api = WXAPIFactory.createWXAPI(mContext, appid, true);
                                if (!api.isWXAppInstalled()) {
                                    nofityError(finalPayListener, receiver, "你的手机没有安装微信");
                                    return;
                                }
                                api.registerApp(appid);
                                PayReq req = new PayReq();
                                req.appId = appid;
                                req.partnerId = wxPayOrderResultBean.getPartnerid();
                                req.prepayId = wxPayOrderResultBean.getPrepayid();
                                req.nonceStr = wxPayOrderResultBean.getNoncestr();
                                req.timeStamp = wxPayOrderResultBean.getTimestamp();
                                req.packageValue = wxPayOrderResultBean.getPackageX();
                                req.sign = wxPayOrderResultBean.getSign();
                                // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信

                                api.sendReq(req);

                            } else {
                                onReqFailed(ResStringUtil.getString(R.string.common_text_pay_request_prepayment_failed));
                            }
                        } catch (Exception e) {
                            onReqFailed(ResStringUtil.getString(R.string.common_text_pay_request_prepayment_failed));

                        }


                    }

                    @Override
                    public void onReqFailed(String errorMsg) {
                        DialogUtils.dismissProgressDialog();
                        nofityError(finalPayListener, receiver, errorMsg);
                    }
                });


    }

    private void nofityError(OnPayListener finalPayListener, BroadcastReceiver receiver, String errorMsg) {
        finalPayListener.onPayFailure(errorMsg, OnPayListener.ERROR);
        LocalBroadcastManager.getInstance(mContext).unregisterReceiver(receiver);
    }

    @Override
    public void setURLAndParams(String url, HashMap paramsMap) {
        this.url = url;
        this.paramsMap = paramsMap;
    }
}
